package com.devgroupvn.dota.youtube;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

public class VidLinkRetriever {
	public static List<Vid> retrieveMP4(String url) {
		List<Vid> vids = retrieve(url);
		for (Iterator<Vid> iterator = vids.iterator(); iterator.hasNext();) {
			Vid vid = (Vid) iterator.next();
			if (!"MP4".equals(vid.getFormat())) {
				iterator.remove();
			} else {
				System.out.println(vid.getLink());
			}
		}
		return vids;
	}

	public static List<Vid> retrieve(String url) {
		List<Vid> result = new ArrayList<Vid>();

		if (url == null)
			return result;

		if (url.contains("youtube.com") || url.contains("youtu.be")) {
			String pageSource = getUrlContent((new StringBuilder()).append(url)
					.append("&fmt=18").toString(), "GET");

			// get video id
			String video_id = getTextBtw(pageSource, "\"video_id\": \"", "\"");
			if (video_id == null)
				video_id = getTextBtw(pageSource, "&video_id=", "&");

			String fmt_url_map = "";
			fmt_url_map = getTextBtw(pageSource, "&amp;url_encoded_fmt_stream_map=", "&");
			if (fmt_url_map != null)
				try {
					fmt_url_map = URLDecoder.decode(fmt_url_map, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			if (fmt_url_map == null)
				fmt_url_map = getTextBtw(pageSource, "\"url_encoded_fmt_stream_map\": \"",
						"\"").replace("\\/", "/");

			String dl_3gplow = null;
			String dl_3gpmed = null;
			String dl_3gphigh = null;
			String dl_flvlow = null;
			String dl_flvmed = null;
			String dl_flvmed2 = null;
			String dl_flvhigh = null;
			String dl_mp4high = null;
			String dl_mp4hd = null;
			String dl_mp4hd2 = null;
			String dl_mp4hd3 = null;

			String fmt_arr[] = fmt_url_map.split(",");
			String arr$[] = fmt_arr;
			int len$ = arr$.length;
			for (int i$ = 0; i$ < len$; i$++) {
				String fmt = arr$[i$];
				String parts[] = fmt.split(Pattern.quote("|"));
				String m_qual, m_url = "";
				try {
//					m_qual = URLDecoder.decode(parts[0], "UTF-8");
//					m_url = URLDecoder.decode(parts[1], "UTF-8");
	                String tempfmtDecode = URLDecoder.decode(fmt, "UTF-8");
				    m_qual = getTextBtw(tempfmtDecode, "&itag=", "&");
				    m_url = URLDecoder.decode(tempfmtDecode.substring(4), "UTF-8");
				    m_url = m_url.replace("\\u0026", "&");
				    
				    int range = m_url.indexOf("&quality=");
				    if (range!=-1)
				    {
				        m_url = m_url.substring(0,range);
				    }
				    else
				    {
				    	range = m_url.indexOf("\\u0026quality=");
				    	m_url = m_url.substring(0,range);
				    }
				        
					if (m_qual.equals("13"))
						dl_3gplow = m_url;
					if (m_qual.equals("17"))
						dl_3gpmed = m_url;
					if (m_qual.equals("36"))
						dl_3gphigh = m_url;
					if (m_qual.equals("5"))
						dl_flvlow = m_url;
					if (m_qual.equals("34"))
						dl_flvmed = m_url;
					if (m_qual.equals("6"))
						dl_flvmed2 = m_url;
					if (m_qual.equals("35"))
						dl_flvhigh = m_url;
					if (m_qual.equals("18"))
						dl_mp4high = m_url;
					if (m_qual.equals("22"))
						dl_mp4hd = m_url;
					if (m_qual.equals("37"))
						dl_mp4hd2 = m_url;
					if (m_qual.equals("38"))
						dl_mp4hd3 = m_url;
					if (m_qual.equals("43"))
						dl_mp4hd2 = m_url;
					if (m_qual.equals("45"))
						dl_mp4hd3 = m_url;
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			
			if (dl_3gplow != null) 
				result.add(new Vid("3GP", "Low Quality", 176, 144, dl_3gplow));
			if (dl_3gpmed != null)
				result.add(new Vid("3GP", "Medium Quality", 176, 144, dl_3gpmed));
			if (dl_3gphigh != null)
				result.add(new Vid("3GP", "High Quality", 320, 240, dl_3gphigh));
			if (dl_flvlow != null)
				result.add(new Vid("FLV", "Low Quality",  400, 226, dl_flvlow));
			if (dl_flvmed2 != null)
				result.add(new Vid("FLV", "Medium Quality", 480, 360, dl_flvmed2));
			if (dl_flvmed != null)
				result.add(new Vid("FLV", "Medium Quality", 640, 360, dl_flvmed));
			if (dl_flvhigh != null)
				result.add(new Vid("FLV", "High Quality", 854, 480, dl_flvhigh));
			if (dl_mp4high != null)
				result.add(new Vid("MP4", "High Quality", 480, 360, dl_mp4high));
			if (dl_mp4hd != null)
				result.add(new Vid("MP4", "High Definition", 1280, 720, dl_mp4hd));
			if (dl_mp4hd2 != null)
				result.add(new Vid("MP4", "High Definition", 1920, 1080, dl_mp4hd2));
			if (dl_mp4hd3 != null)
				result.add(new Vid("MP4", "Epic Definition", 4096, 2304, dl_mp4hd3));
		}

		
		return result;
	}
	
	/*private static String replaceOldChar(String input, String oldS, String newS)
	{
		char[] temp = new char[newS.length()];
		int k = 0;
		for(int i = 0; i < input.length(); i++)
		{
			k = i + 1;
			input.getChars(i, k, temp, 0);
			input.
		}
		return "";
	}*/

	public static String getTextBtw(String source, String lBound, String rBound) {
		try {
			String arr1[];
			String arr2[];
			arr1 = source.split(lBound);
			arr2 = arr1[1].split(rBound);
			if (arr2[0] == null)
				return arr1[1];
			return arr2[0];
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private static String getUrlContent(String url, String httpMethod) {
		try {
			ByteArrayOutputStream output;
			URL u = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) u.openConnection();

			conn.setRequestMethod(httpMethod);

			conn.setRequestProperty(
					"User-Agent",
					"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.17) Gecko/20110422 Ubuntu/10.10 (maverick) Firefox/3.6.17");
			conn.setRequestProperty("Accept",
					"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
			conn.setRequestProperty("Accept-Language", "en-us,en;q=0.5");
			conn.setRequestProperty("Accept-Charset",
					"ISO-8859-1,utf-8;q=0.7,*;q=0.7");
			conn.setRequestProperty("Keep-Alive", "115");
			conn.setRequestProperty("Connection", "keep-alive");
			conn.setRequestProperty("Referer", "http://www.youtube.com/");
			conn.setRequestProperty("Cookie", "");
			conn.setRequestProperty("Cache-Control", "max-age=0");

			InputStream is = conn.getInputStream();
			output = new ByteArrayOutputStream();
			byte buffer[] = new byte[1024];
			for (int bytesRead = 0; (bytesRead = is.read(buffer)) != -1;)
				output.write(buffer, 0, bytesRead);

			return output.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
}
